package com.dgut.legalservice.tool;

import com.dgut.legalservice.domain.contract.Contract;
import com.dgut.legalservice.domain.contract.ContractItem;
import com.dgut.legalservice.domain.contract.ContractStep;
import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.impl.xb.xmlschema.SpaceAttribute;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

import java.math.BigInteger;

public class DocumentTool {

    public static XWPFDocument createDocument(Contract contract) {
        //生成word文档
        XWPFDocument doc = new XWPFDocument();
        //必须有样式文档，即使它是空的
        XWPFStyles styles = doc.createStyles();
//        addCustomHeadingStyle(doc, "正文", 1);
//        addCustomHeadingStyle(doc, "标题 1", 2);
        //必须有至少页面大小设置的页面的部分属性
        CTSectPr sectPr = doc.getDocument().getBody().addNewSectPr();
        CTPageSz pgsz = sectPr.isSetPgSz() ? sectPr.getPgSz() : sectPr.addNewPgSz();
        pgsz.setH(BigInteger.valueOf(16840));
        pgsz.setW(BigInteger.valueOf(11907));
        //页边距
        CTPageMar ctpagemar = sectPr.addNewPgMar();
        ctpagemar.setLeft(BigInteger.valueOf(1803));
        ctpagemar.setTop(BigInteger.valueOf(1440));
        ctpagemar.setRight(BigInteger.valueOf(1803));
        ctpagemar.setBottom(BigInteger.valueOf(1440));
//        setDocumentMargin(doc, "1803", "1440", "1803", "1440");
        //页眉页码
        createDefaultHeader(doc,"");
        createDefaultFooter(doc);
        //添加标题
        XWPFParagraph titleParagraph = doc.createParagraph();
        titleParagraph.setAlignment(ParagraphAlignment.CENTER);//设置段落居中
//        titleParagraph.setSpacingBetween(1.5);//行间距1.5倍
//        titleParagraph.setStyle("正文");
        XWPFRun titleParagraphRun = titleParagraph.createRun();
        titleParagraphRun.setText(contract.getName());
        titleParagraphRun.setColor("000000");
        titleParagraphRun.setFontFamily("宋体");
        titleParagraphRun.setFontSize(14);
//        titleParagraphRun.setTextPosition(30);

        XWPFParagraph paragraph;
        XWPFRun run;
        //段落
        if (contract.getContractSteps() != null) {
            for (ContractStep contractStep : contract.getContractSteps()) {
                if (contractStep.getContractItems() != null) {
                    for (ContractItem contractItem : contractStep.getContractItems()) {
                        String[] subContent = contractItem.getAttributeValue().split("\r\n");
                        for (String str : subContent) {
                            paragraph = doc.createParagraph();
                            paragraph.setSpacingBetween(1.5);
//                            paragraph.setStyle("正文");
                            run = paragraph.createRun();
                            run.setText(str);
                            run.setColor("000000");
                            run.setFontFamily("宋体");
                            run.setFontSize(14);
//                            run.setTextPosition(30);
                        }
                    }
                }
            }
        }
        return doc;
    }

    /**
     * 增加自定义标题样式，stackoverflow源码
     *
     * @param docxDocument 目标文档
     * @param strStyleId 样式名称
     * @param headingLevel 样式级别
     */
    private static void addCustomHeadingStyle(XWPFDocument docxDocument, String strStyleId, int headingLevel) {
        CTStyle ctStyle = CTStyle.Factory.newInstance();
        ctStyle.setStyleId(strStyleId);

        CTString styleName = CTString.Factory.newInstance();
        styleName.setVal(strStyleId);
        ctStyle.setName(styleName);

        CTDecimalNumber indentNumber = CTDecimalNumber.Factory.newInstance();
        indentNumber.setVal(BigInteger.valueOf(headingLevel));

        // lower number > style is more prominent in the formats bar
        ctStyle.setUiPriority(indentNumber);

        CTOnOff onoffnull = CTOnOff.Factory.newInstance();
        ctStyle.setUnhideWhenUsed(onoffnull);

        // style shows up in the formats bar
        ctStyle.setQFormat(onoffnull);

        // style defines a heading of the given level
        CTPPr ppr = CTPPr.Factory.newInstance();
        ppr.setOutlineLvl(indentNumber);
        ctStyle.setPPr(ppr);

        XWPFStyle style = new XWPFStyle(ctStyle);

        // is a null op if already defined
        XWPFStyles styles = docxDocument.createStyles();

        style.setType(STStyleType.PARAGRAPH);
        styles.addStyle(style);

    }

    public static void createDefaultHeader(final XWPFDocument docx, final String text) {
        CTP ctp = CTP.Factory.newInstance();
        XWPFParagraph paragraph = new XWPFParagraph(ctp, docx);
        ctp.addNewR().addNewT().setStringValue(text);
        ctp.addNewR().addNewT().setSpace(SpaceAttribute.Space.PRESERVE);
        CTSectPr sectPr = docx.getDocument().getBody().isSetSectPr() ? docx.getDocument().getBody().getSectPr() : docx.getDocument().getBody().addNewSectPr();
        XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(docx, sectPr);
        XWPFHeader header = policy.createHeader(STHdrFtr.DEFAULT, new XWPFParagraph[]{paragraph});
        header.setXWPFDocument(docx);
    }


    public static void createDefaultFooter(final XWPFDocument docx) {
        CTP pageNo = CTP.Factory.newInstance();
        XWPFParagraph footer = new XWPFParagraph(pageNo, docx);
        CTPPr begin = pageNo.addNewPPr();
//        begin.addNewPStyle().setVal(STYLE_FOOTER);
        begin.addNewJc().setVal(STJc.CENTER);
        pageNo.addNewR().addNewFldChar().setFldCharType(STFldCharType.BEGIN);
        pageNo.addNewR().addNewInstrText().setStringValue("PAGE   \\* MERGEFORMAT");
        pageNo.addNewR().addNewFldChar().setFldCharType(STFldCharType.SEPARATE);
        CTR end = pageNo.addNewR();
        CTRPr endRPr = end.addNewRPr();
        endRPr.addNewNoProof();
//        endRPr.addNewLang().setVal(LANG_ZH_CN);
        end.addNewFldChar().setFldCharType(STFldCharType.END);
        CTSectPr sectPr = docx.getDocument().getBody().isSetSectPr() ? docx.getDocument().getBody().getSectPr() : docx.getDocument().getBody().addNewSectPr();
        XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(docx, sectPr);
        policy.createFooter(STHdrFtr.DEFAULT, new XWPFParagraph[]{footer});
    }

/*    *//**
     * 设置页边距 (word中1厘米约等于567)
     * @param document
     * @param left
     * @param top
     * @param right
     * @param bottom
     *//*
    public static void setDocumentMargin(XWPFDocument document, String left,String top, String right, String bottom) {
        CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();
        CTPageMar ctpagemar = sectPr.addNewPgMar();
        if (StringUtils.isNotBlank(left)) {
            ctpagemar.setLeft(new BigInteger(left));
        }
        if (StringUtils.isNotBlank(top)) {
            ctpagemar.setTop(new BigInteger(top));
        }
        if (StringUtils.isNotBlank(right)) {
            ctpagemar.setRight(new BigInteger(right));
        }
        if (StringUtils.isNotBlank(bottom)) {
            ctpagemar.setBottom(new BigInteger(bottom));
        }
    }*/

    /**
     * 设置页面大小及纸张方向 landscape横向
     * @param document
     * @param width
     * @param height
     * @param stValue
     */
    public static void setDocumentSize(XWPFDocument document, String width,String height, STPageOrientation.Enum stValue) {
        CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();
        CTPageSz pgsz = sectPr.isSetPgSz() ? sectPr.getPgSz() : sectPr.addNewPgSz();
        pgsz.setH(new BigInteger(height));
        pgsz.setW(new BigInteger(width));
        pgsz.setOrient(stValue);
    }
}
